package cn.kgc.mybatis.web.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 课工场
 * @date 2024/10/25
 * @description
 */
public class MybatisUtil {

    private static SqlSessionFactory factory;

    static {

        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static SqlSession createSqlSession(){

        //事务不会自动提交
        // SqlSession sqlSession = factory.openSession();

        // 自动提交事务
        SqlSession sqlSession = factory.openSession(true);

        return sqlSession;
    }


    public static Object getMapperProxy(Class clazz){
        // 自动提交事务
        SqlSession sqlSession = factory.openSession(true);
        return sqlSession.getMapper(clazz);
    }


    // 方法中如何使用泛型
    public static <T> T creatMapperProxy(Class<T> clazz){
        // 自动提交事务
        SqlSession sqlSession = factory.openSession(true);
        return sqlSession.getMapper(clazz);
    }



}
